//
//  CssPointView.m
//  wuliangye
//
//  Created by yeeyuntech on 16/8/4.
//  Copyright © 2016年 jarze. All rights reserved.
//
#import "CssPointView.h"

#define DEGREES_TO_RADIANS(degrees) (degrees) / 180.0 * M_PI

#define RGB(r,g,b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0]
#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a/255.0]
#define CGRGB(r,g,b) RGB(r,g,b).CGColor
#define iCGRGB(r,g,b) (id)CGRGB(r,g,b)
#define CGRGBA(r,g,b,a) RGBA(r,g,b,a).CGColor
#define iCGRGBA(r,g,b,a) (id)CGRGBA(r,g,b,a)

@interface CssPointView()

@property (nonatomic) bool showInnerBackground;
@property (nonatomic) bool showInnerRim;
@property (nonatomic) CGFloat innerRimWidth;
@property (nonatomic) CGFloat innerRimBorderWidth;

//指针
@property (nonatomic) CGFloat needleWidth;
@property (nonatomic) CGFloat needleHeight;
@property (nonatomic) CGFloat needleScrewRadius;

// 刻度
@property (nonatomic) CGFloat scaleDivisionsLength;
@property (nonatomic) CGFloat scaleDivisionsWidth;
@property (nonatomic) CGFloat scaleSubdivisionsLength;
@property (nonatomic) CGFloat scaleSubdivisionsWidth;

@property (nonatomic) CGFloat scalePosition;

@property (nonatomic) CGFloat scaleDivisions;
@property (nonatomic) CGFloat scaleSubdivisions;
@property (nonatomic) bool showScaleShadow;

@property (nonatomic, strong) UIColor *scaleDivisionColor;
@property (nonatomic, strong) UIColor *scaleSubDivisionColor;
@end
@implementation CssPointView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


{
    CGRect fullRect;
    CGRect innerRimRect;
    CGRect innerRimBorderRect;
    CGRect faceRect;
    CGRect rangeLabelsRect;
    CGRect scaleRect;
    CGPoint center;
    CGFloat scaleRotation;
    CGFloat divisionValue;
    CGFloat subdivisionValue;
    CGFloat subdivisionAngle;
    double currentValue;
    double needleAcceleration;
    double needleVelocity;
    NSTimeInterval needleLastMoved;
    UIImage *background;
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initialize];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self initialize];
    
}
- (void)initialize {
    
    _showInnerRim = NO;
    _showInnerBackground = YES;
    _innerRimWidth = 0.05;
    _innerRimBorderWidth = 0.005;
//    _innerBackgroundStyle = WMGaugeViewInnerBackgroundStyleGradient;
    
    _needleWidth = 0.035;
    _needleHeight = 0.34;
    _needleScrewRadius = 0.04;
//    _needleStyle = WMGaugeViewNeedleStyle3D;
//    _needleScrewStyle = WMGaugeViewNeedleScrewStyleGradient;
    
    _scalePosition = 0.025;
    _scaleStartAngle = 30.0;
    _scaleEndAngle = 330.0;
    _scaleDivisions = 12.0;
    _scaleSubdivisions = 10.0;
    _showScaleShadow = YES;
//    _scalesubdivisionsaligment = WMGaugeViewSubdivisionsAlignmentTop;
    _scaleDivisionsLength = 0.045;
    _scaleDivisionsWidth = 0.01;
    _scaleSubdivisionsLength = 0.015;
    _scaleSubdivisionsWidth = 0.01;
    
    _value = 0.0;
    _minValue = 0.0;
    _maxValue = 240.0;
    currentValue = 0.0;
    
    needleVelocity = 0.0;
    needleAcceleration = 0.0;
    needleLastMoved = -1;
    
    background = nil;
    
    _showRangeLabels = NO;
    _rangeLabelsWidth = 0.04;
    _rangeLabelsFontKerning = 1.0;
    _rangeValues = nil;
    _rangeColors = nil;
    _rangeLabels = nil;
    
    _scaleDivisionColor = RGB(68, 84, 105);
    _scaleSubDivisionColor = RGB(217, 217, 217);
    
    _scaleFont = nil;
    
//    _unitOfMeasurement = @"";
//    _showUnitOfMeasurement = NO;
    
    
    
    
    
    
    [self initDrawingRects];
    [self initScale];
    

//    _unitOfMeasurement = @"psi";
//    _showUnitOfMeasurement = YES;
    

    
    
    //指针
//    _needleWidth = 10;
//    _needleHeight = 85;
//    _needleScrewRadius = 10;
    //刻度
//    _scaleDivisions = 4;
//    _scaleSubdivisions = 10.0;
//    _showScaleShadow = YES;
//    
//    _scaleDivisionsLength = 10;
//    _scaleDivisionsWidth = 2;
//    _scaleSubdivisionsLength = 15;
//    _scaleSubdivisionsWidth = 1;
//    
//    _scaleDivisionColor = RGB(68, 84, 105);
//    _scaleSubDivisionColor = RGB(217, 217, 217);
//    
//    _scalePosition = 2;
//    [self initDrawingRects];
//    [self initScale];
    
}

- (void)initDrawingRects
{
    center = CGPointMake(0.5, 0.5);
    fullRect = CGRectMake(0.0, 0.0, 1.0, 1.0);
    
    _innerRimBorderWidth = _showInnerRim?_innerRimBorderWidth:0.0;
    _innerRimWidth = _showInnerRim?_innerRimWidth:0.0;
    
    innerRimRect = fullRect;
    innerRimBorderRect = CGRectMake(innerRimRect.origin.x + _innerRimBorderWidth,
                                    innerRimRect.origin.y + _innerRimBorderWidth,
                                    innerRimRect.size.width - 2 * _innerRimBorderWidth,
                                    innerRimRect.size.height - 2 * _innerRimBorderWidth);
    faceRect = CGRectMake(innerRimRect.origin.x + _innerRimWidth,
                          innerRimRect.origin.y + _innerRimWidth,
                          innerRimRect.size.width - 2 * _innerRimWidth,
                          innerRimRect.size.height - 2 * _innerRimWidth);
    rangeLabelsRect = CGRectMake(faceRect.origin.x + (_showRangeLabels ? _rangeLabelsWidth : 0.0),
                                 faceRect.origin.y + (_showRangeLabels ? _rangeLabelsWidth : 0.0),
                                 faceRect.size.width - 2 * (_showRangeLabels ? _rangeLabelsWidth : 0.0),
                                 faceRect.size.height - 2 * (_showRangeLabels ? _rangeLabelsWidth : 0.0));
    scaleRect = CGRectMake(rangeLabelsRect.origin.x + _scalePosition,
                           rangeLabelsRect.origin.y + _scalePosition,
                           rangeLabelsRect.size.width - 2 * _scalePosition,
                           rangeLabelsRect.size.height - 2 * _scalePosition);
}

- (void)drawRect:(CGRect)rect
{
    [self computeCurrentValue];
    
    if (background == nil)
    {
        UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        //画图大小比例缩放
        CGContextScaleCTM(context, rect.size.width , rect.size.height);
//        [self drawGauge:context];
        [self drawScale:context];
        [self drawRangeLabels:context];
        background = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    [background drawInRect:rect];
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(context, rect.size.width , rect.size.height);

    [self drawNeedle:context];
}

- (void)drawRangeLabels:(CGContextRef)context
{
    CGContextSaveGState(context);
    
//    NSString *str = @"内存卡大v";
//    [str drawAtPoint:CGPointMake(0 , 64) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:[UIColor redColor]}];
    
    //旋转角度
    [self rotateContext:context fromCenter:center withAngle:DEGREES_TO_RADIANS(90 + _scaleStartAngle)];
    
//    CGContextSetShadow(context, CGSizeMake(0.0, 0.0), 0.0);
    
    CGFloat maxAngle = _scaleEndAngle - _scaleStartAngle;
    CGFloat lastStartAngle = 0.0f;
    
    
//    CGContextSetLineCap(context, kCGLineCapRound);


    for (int i = 0; i < _rangeValues.count; i ++)
    {
        float value = ((NSNumber*)[_rangeValues objectAtIndex:i]).floatValue;
        float valueAngle = (value - _minValue) / (_maxValue - _minValue) * maxAngle;
        
        //＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path addArcWithCenter:center radius:rangeLabelsRect.size.width / 2.0 startAngle:DEGREES_TO_RADIANS(lastStartAngle) endAngle:DEGREES_TO_RADIANS(valueAngle) clockwise:YES];
        UIColor *color = _rangeColors[i];
        [color setStroke];
        [path setLineCapStyle:kCGLineCapRound];
        path.lineWidth = _rangeLabelsWidth;
        [path stroke];
        
        //＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊
//        CGContextSetStrokeColorWithColor(context, color.CGColor);//设置线条填充色
//        CGContextSetLineWidth(context, _rangeLabelsWidth);
//        CGContextAddArc(context, 250, 150, rangeLabelsRect.size.width / 2.0, DEGREES_TO_RADIANS(lastStartAngle), DEGREES_TO_RADIANS(valueAngle), 0);
//        CGContextStrokePath(context);
        
        //画字
        [self drawStringAtContext:context string:(NSString*)_rangeLabels[i] withCenter:center radius:rangeLabelsRect.size.width / 2.0 startAngle:DEGREES_TO_RADIANS(lastStartAngle) endAngle:DEGREES_TO_RADIANS(valueAngle)];
        
        lastStartAngle = valueAngle;
    }
    
    CGContextRestoreGState(context);
}


// 旋转
- (void)rotateContext:(CGContextRef)context fromCenter:(CGPoint)center_ withAngle:(CGFloat)angle
{
    CGContextTranslateCTM(context, center_.x, center_.y);
    CGContextRotateCTM(context, angle);
    CGContextTranslateCTM(context, -center_.x, -center_.y);
}

//画字符串
- (void) drawStringAtContext:(CGContextRef) context string:(NSString*)text withCenter:(CGPoint)center_ radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle
{
//    苹果设置一个保存图形上下文的栈,来随时存储当前你的图形上下文
//    通过
//    CGContextSaveGState(context)；
//    来保存(推入)图形上下文到栈顶
//    在绘制(渲染之后),通过
//    CGContextRestoreGState(context);
//    来更新(将之前入栈的图形上下文状态出栈,将当前的图形上下文状态入栈)图形上下到栈顶
//    注意:这两个代码一般成对出现, 这样既保护了图形上下文状态的唯一性,也方便了在需要的地方修改图形上下状态
    CGContextSaveGState(context);
    
//    UIFont* font = _scaleFont?_scaleFont:[UIFont fontWithName:@"Helvetica" size:0.05];
    NSDictionary* stringAttrs = @{ NSFontAttributeName : [UIFont systemFontOfSize:0.05], NSForegroundColorAttributeName : [UIColor blackColor] };
    //文字长度
    CGSize textSize = [text sizeWithAttributes:stringAttrs];
    //圆周长
    float perimeter = 2 * M_PI * radius;
    //字幅度角
    float textAngle = textSize.width / perimeter * 2 * M_PI * _rangeLabelsFontKerning;
    float offset = ((endAngle - startAngle) - textAngle) / 2.0;
    float letterPosition = 0;

    //旋转字符串到计算的位置
    [self rotateContext:context fromCenter:center withAngle:startAngle + offset];
    
    //画每个字符
    for (int index = 0; index < [text length]; index++)
    {
        //取出字符
        NSRange range = {index, 1};
        NSString* letter = [text substringWithRange:range];
        NSAttributedString* attrStr = [[NSAttributedString alloc] initWithString:letter attributes:stringAttrs];
        
        CGSize charSize = [letter sizeWithAttributes:stringAttrs];
        
        //字符位置长度
        letterPosition += (charSize.width / 2);
//        - kerning;
        
        float angle = (letterPosition / perimeter * 2 * M_PI) * _rangeLabelsFontKerning;
        
        //字符坐标
        CGPoint letterPoint = CGPointMake((radius) * cos(angle) + center_.x, (radius) * sin(angle) + center_.y);

#warning *****************????????????????????????????????
        //字符旋转
        CGContextSaveGState(context);
        
//        移动函数平移变换根据我们指定的x, y轴的值移动坐标系统的原点。
        CGContextTranslateCTM(context, letterPoint.x, letterPoint.y);
        //旋转
        CGAffineTransform rotationTransform = CGAffineTransformMakeRotation(angle + M_PI_2);
        CGContextConcatCTM(context, rotationTransform);
        CGContextTranslateCTM(context, -letterPoint.x, -letterPoint.y);
        
        //字符位置原点在左上角，调整到中心位置
        [attrStr drawAtPoint:CGPointMake(letterPoint.x - charSize.width/2 , letterPoint.y - charSize.height / 2)];

        CGContextRestoreGState(context);
        
        //保存字符结束的位置
        letterPosition += charSize.width / 2;
    }
    CGContextRestoreGState(context);
}






- (void)drawNeedle:(CGContextRef)context
{
    [self rotateContext:context fromCenter:center withAngle:DEGREES_TO_RADIANS(180 + _scaleStartAngle + (currentValue - _minValue) / (_maxValue - _minValue) * (_scaleEndAngle - _scaleStartAngle))];
    
//    switch (_needleStyle)
//    {
//        case WMGaugeViewNeedleStyle3D:
//        {
            CGContextSetShadow(context, CGSizeMake(1, 1), 8.0);
            // Left Needle
            UIBezierPath *leftNeedlePath = [UIBezierPath bezierPath];
            [leftNeedlePath moveToPoint:center];
            [leftNeedlePath addLineToPoint:CGPointMake(center.x - _needleWidth, center.y)];
            [leftNeedlePath addLineToPoint:CGPointMake(center.x, center.y - _needleHeight)];
            [leftNeedlePath closePath];
            [RGB(176, 10, 19) setFill];
            [leftNeedlePath fill];
            
            // Right Needle
            UIBezierPath *rightNeedlePath = [UIBezierPath bezierPath];
            [rightNeedlePath moveToPoint:center];
            [rightNeedlePath addLineToPoint:CGPointMake(center.x + _needleWidth, center.y)];
            [rightNeedlePath addLineToPoint:CGPointMake(center.x, center.y - _needleHeight)];
            [rightNeedlePath closePath];
            [RGB(252, 18, 30) setFill];
            [rightNeedlePath fill];
//        }
//            break;
//            
//        case WMGaugeViewNeedleStyleFlatThin:
//        {
//            UIBezierPath *needlePath = [UIBezierPath bezierPath];
//            [needlePath moveToPoint:CGPointMake(center.x - _needleWidth, center.y)];
//            [needlePath addLineToPoint:CGPointMake(center.x + _needleWidth, center.y)];
//            [needlePath addLineToPoint:CGPointMake(center.x, center.x - _needleHeight)];
//            [needlePath closePath];
//            
//#define SHADOW_OFFSET  0.008
//            CGContextTranslateCTM(context, -SHADOW_OFFSET, -SHADOW_OFFSET);
//            [RGBA(0, 0, 0, 40) setFill];
//            [RGBA(0, 0, 0, 20) setStroke];
//            [needlePath fill];
//            needlePath.lineWidth = 0.004;
//            [needlePath stroke];
//            CGContextTranslateCTM(context, SHADOW_OFFSET, SHADOW_OFFSET);
//            
//            [RGB(255, 104, 97) setFill];
//            [RGB(255, 104, 97) setStroke];
//            [needlePath fill];
//            needlePath.lineWidth = 0.004;
//            [needlePath stroke];
//        }
//            break;
//            
//        default:
//            break;
//    }
    
    [self drawNeedleScrew:context];
}

- (void)drawNeedleScrew:(CGContextRef)context
{
//    switch (_needleScrewStyle)
//    {
//        case WMGaugeViewNeedleScrewStyleGradient:
//        {
            // Screw
            CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
            CGGradientRef gradient = CGGradientCreateWithColors(baseSpace, (CFArrayRef)@[iCGRGB(171, 171, 171), iCGRGB(255, 255, 255), iCGRGB(171, 171, 171)], (const CGFloat[]){0.05, 0.9, 1.00});
            CGColorSpaceRelease(baseSpace), baseSpace = NULL;
            CGContextAddEllipseInRect(context, CGRectMake(center.x - _needleScrewRadius, center.y - _needleScrewRadius, _needleScrewRadius * 2.0, _needleScrewRadius * 2.0));
            CGContextClip(context);
            CGContextDrawRadialGradient(context, gradient, center, 0, center, _needleScrewRadius * 2.0, kCGGradientDrawsAfterEndLocation);
            CGGradientRelease(gradient), gradient = NULL;
            // 释放色彩空间
            CGColorSpaceRelease(baseSpace);
    
//            // Border
//            CGContextSetLineWidth(context, 0.005);
//            CGContextSetStrokeColorWithColor(context, CGRGBA(81, 84, 89, 100));
//            CGContextAddEllipseInRect(context, CGRectMake(center.x - _needleScrewRadius, center.y - _needleScrewRadius, _needleScrewRadius * 2.0, _needleScrewRadius * 2.0));
//            CGContextStrokePath(context);
//        }
//            break;
//            
//        case WMGaugeViewNeedleScrewStylePlain:
//        {
//            CGContextAddEllipseInRect(context, CGRectMake(center.x - _needleScrewRadius, center.y - _needleScrewRadius, _needleScrewRadius * 2.0, _needleScrewRadius * 2.0));
//            CGContextSetFillColorWithColor(context, CGRGB(68, 84, 105));
//            CGContextFillPath(context);
//        }
//            break;
//            
//        default:
//            break;
//    }
}

- (void)drawScale:(CGContextRef)context
{
    CGContextSaveGState(context);
    [self rotateContext:context fromCenter:center withAngle:DEGREES_TO_RADIANS(180 + _scaleStartAngle)];
    
    int totalTicks = _scaleDivisions * _scaleSubdivisions + 1;
    for (int i = 0; i < totalTicks; i++)
    {
        CGFloat offset = 0.0;
//        offset = (_scaleDivisionsLength - _scaleSubdivisionsLength) / 2.0;
//        if (_scalesubdivisionsaligment == WMGaugeViewSubdivisionsAlignmentCenter)
//        offset = (_scaleDivisionsLength - _scaleSubdivisionsLength) / 2.0;
//        if (_scalesubdivisionsaligment == WMGaugeViewSubdivisionsAlignmentBottom)
//        offset = _scaleDivisionsLength - _scaleSubdivisionsLength;
        
        CGFloat y1 = scaleRect.origin.y;
        CGFloat y2 = y1 + _scaleSubdivisionsLength;
        CGFloat y3 = y1 + _scaleDivisionsLength;
        
        float value = [self valueForTick:i];
//        float div = (_maxValue - _minValue) / _scaleDivisions;
        //每大格范围值
        float div = divisionValue;
        
        
        float mod = (int)value % (int)div;
        
        if ((fabsf(mod - 0) < 0.000001) || (fabsf(mod - div) < 0.000001))
        {
            UIColor *color = (_rangeValues && _rangeColors)?[self rangeColorForValue:value]:_scaleDivisionColor;
//            UIColor *color = [UIColor blackColor];
            CGContextSetStrokeColorWithColor(context, color.CGColor);
            CGContextSetLineWidth(context, _scaleDivisionsWidth);
            CGContextSetShadow(context, CGSizeMake(0.05, 0.05), _showScaleShadow?2.0:0.0);
            
            CGContextMoveToPoint(context, 0.5, y1);
            CGContextAddLineToPoint(context, 0.5, y3);
            CGContextStrokePath(context);
            
            NSString *valueString = [NSString stringWithFormat:@"%0.0f",value];

            UIFont* font = _scaleFont?_scaleFont:[UIFont fontWithName:@"Helvetica-Bold" size:0.05];
            NSDictionary* stringAttrs = @{ NSFontAttributeName : font, NSForegroundColorAttributeName : color };
        
//            NSDictionary* stringAttrs = @{ NSFontAttributeName : [UIFont systemFontOfSize:12], NSForegroundColorAttributeName : [UIColor blackColor] };
        
            NSAttributedString* attrStr = [[NSAttributedString alloc] initWithString:valueString attributes:stringAttrs];
            CGSize fontWidth = [valueString sizeWithAttributes:stringAttrs];
            [attrStr drawAtPoint:CGPointMake(0.5 - fontWidth.width / 2.0, y3 + 0.005)];
            NSLog(@"%@--x:%f---y:%f", valueString,0.5 - fontWidth.width / 2.0,y3 + 0.005 );
        }
        else
        {
            UIColor *color = (_rangeValues && _rangeColors)?[self rangeColorForValue:value]:_scaleSubDivisionColor;
            CGContextSetStrokeColorWithColor(context, color.CGColor);
            CGContextSetLineWidth(context, _scaleSubdivisionsWidth);
            CGContextMoveToPoint(context, 0.5, y1);
            if (_showScaleShadow) CGContextSetShadow(context, CGSizeMake(0.05, 0.05), 2.0);
            
            CGContextMoveToPoint(context, 0.5, y1 + offset);
            CGContextAddLineToPoint(context, 0.5, y2 + offset);
            CGContextStrokePath(context);
        }
        
        [self rotateContext:context fromCenter:center withAngle:DEGREES_TO_RADIANS(subdivisionAngle)];
    }
    CGContextRestoreGState(context);
    
}
- (void)initScale
{
    //_scaleDivisions  大格数
    //_scaleSubdivisions 每大格中小格数
    
    //初始旋转角度
    scaleRotation = (int)(_scaleStartAngle + 180) % 360;
    
    //每大格范围值
    divisionValue = (_maxValue - _minValue) / _scaleDivisions;
    
    //每小格范围值
    subdivisionValue = divisionValue / _scaleSubdivisions;
    
    //每小格角度
    subdivisionAngle = (_scaleEndAngle - _scaleStartAngle) / (_scaleDivisions * _scaleSubdivisions);
}

- (float)valueForTick:(int)tick
{
    return tick * (divisionValue / _scaleSubdivisions) + _minValue;
}

//取各色区颜色
- (UIColor*)rangeColorForValue:(float)value
{
    NSInteger length = _rangeValues.count;
    for (int i = 0; i < length - 1; i++)
    {
        if (value < [_rangeValues[i] floatValue])
            return _rangeColors[i];
    }
    if (value <= [_rangeValues[length - 1] floatValue])
        return _rangeColors[length - 1];
    return nil;
}


- (void)computeCurrentValue
{
    if (currentValue == _value)
        return;
    
    if (-1 != needleLastMoved)
    {
        NSTimeInterval time = ([[NSDate date] timeIntervalSince1970] - needleLastMoved);
        
        needleAcceleration = 5.0 * (_value - currentValue);
        currentValue += needleVelocity * time;
        needleVelocity += needleAcceleration * time * 2.0;
        
        if (fabs(_value - currentValue) < (_maxValue - _minValue) * 0.01)
        {
            currentValue = _value;
            needleVelocity = 0.0;
            needleAcceleration = 0.0;
            needleLastMoved = -1;
        }
        else
        {
            needleLastMoved =  [[NSDate date] timeIntervalSince1970];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^(void)
                       {
                           [self setNeedsDisplay];
                       });
    }
    else
    {
        needleLastMoved =  [[NSDate date] timeIntervalSince1970];
        [self computeCurrentValue];
    }
}
#pragma mark - Properties

- (void)setValue:(float)value
{
    if (value > _maxValue)
        _value = _maxValue;
    else if (value < _minValue)
        _value = _minValue;
    else
        _value = value;
    
    needleVelocity = 0.0;
    needleAcceleration = 0.0;
    needleLastMoved = -1;
    
    [self setNeedsDisplay];
}

- (void)setValue:(float)value animated:(BOOL)animated
{
    self.value = value;
    if (!animated)
        currentValue = _value;
}

- (void)setRangeLabelsWidth:(CGFloat)rangeLabelsWidth
{
    _rangeLabelsWidth = rangeLabelsWidth;
    [self invalidateBackground];
}

- (void)setMinValue:(float)minValue
{
    _minValue = minValue;
    [self invalidateBackground];
}

- (void)setMaxValue:(float)maxValue
{
    _maxValue = maxValue;
    [self invalidateBackground];
}

- (void)setRangeValues:(NSArray *)rangeValues
{
    _rangeValues = rangeValues;
    [self invalidateBackground];
}

- (void)setRangeColors:(NSArray *)rangeColors
{
    _rangeColors = rangeColors;
    [self invalidateBackground];
}

- (void)setRangeLabels:(NSArray *)rangeLabels
{
    _rangeLabels = rangeLabels;
    [self invalidateBackground];
}
- (void)setUnitOfMeasurement:(NSString *)unitOfMeasurement
{
    _unitOfMeasurement = unitOfMeasurement;
    [self invalidateBackground];
}

- (void)setShowUnitOfMeasurement:(bool)showUnitOfMeasurement
{
    _showUnitOfMeasurement = showUnitOfMeasurement;
    [self invalidateBackground];
}


- (void)invalidateBackground
{
    background = nil;
    [self initDrawingRects];
    [self initScale];
    [self setNeedsDisplay];
}
@end
